package edu.uoc.tfc.web.tags;



import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.apache.commons.lang.StringUtils;



public class CheckboxTag extends AbstractFormFieldTag 
{



    private static final long serialVersionUID = 1L;



    private boolean checked = false;



	public boolean isChecked() {
	    return checked;
    }



	public void setChecked(boolean checked) {
	    this.checked = checked;
    }



	@Override
	public int doStartTag() throws JspException
	{
		try
		{
			initialize();
			JspWriter out = pageContext.getOut();
			write(out,"<div id=\"" + getId() + "-control\">");
			write(out,"<label class=\"checkbox\">");
			
			String checked;
			if (
				isChecked() ||
				StringUtils.equals(getValue(), Boolean.TRUE.toString())
			){
				checked = " checked=\"checked\"";
			}
			else
			{
				checked = "";
			}
			
			String disabled = "";
			if (this.isReadonly() || getForm().isReadonly()) {
				disabled = "disabled";
			}
			
			write(out,"<input type=\"checkbox\" " +
					" name=\"" + getName() + "\" " +
					" id=\"" + getId() + "\"" +
					" " + checked + " " +
					" " + disabled + " " +
					" />");
			
			write(out,getMessage(getLabel(), null));
			write(out,"</label>");
			write(out,"</div>");
		}
		catch (Exception ex)
		{
			throw new JspException(ex);
		}

		return SKIP_BODY;
	}



	@Override
	public int doEndTag() throws JspException
	{
		return EVAL_PAGE;
	}



	@Override
	protected void doStartFormField(JspWriter out) throws JspException
	{
		// No hacemos nada
	}



	@Override
    protected void doEndFormField(JspWriter out) throws JspException
    {
		// No hacemos nada
    }



	@Override
    protected void writeLabel(JspWriter out) throws Exception
    {
		// Sobreescribimos la escritura de label porque los radio tienen su propia label.
		// No hacemos nada
    }



}
